package com.example.ps_online;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public  void verifyStoragePermissions(Activity activity) {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_PERMISSION_STORAGE = 100;
            String[] permissions = {
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };

            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    this.requestPermissions(permissions, REQUEST_CODE_PERMISSION_STORAGE);
                    return;
                }
            }
        }
    }



    private Button mBtnLoading, del;
    private ImageView mImage;
    private String URLPATH = null;
    private final static String FILEPATH = Environment.getExternalStorageDirectory() + "/支付宝图片";
    private Bitmap mBitmap;
    private ProgressDialog mProgressDialog;
    private File file;
    private File dirfile;
    private EditText username, money;
    private Spinner spinner;
    private String names;
    private String prices;
    private int type = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        verifyStoragePermissions(this);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mBtnLoading = findViewById(R.id.btn_loading);
        del = findViewById(R.id.del_all);
        del.setOnClickListener(this);
        mBtnLoading.setOnClickListener(this);
        mImage = findViewById(R.id.image);

        username = findViewById(R.id.name);
        money = findViewById(R.id.money);
        spinner = findViewById(R.id.type);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                type = position + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_loading:
                String u = username.getText().toString();
                String m = money.getText().toString();
                if (u.trim().length() == 0 || m.trim().length() == 0) {
                    Toast.makeText(getApplicationContext(), "请填写好数据", Toast.LENGTH_LONG).show();
                    return;
                }
                names=u;
                prices=m;

                Toast.makeText(getApplicationContext(),"下载中，请稍等片刻",Toast.LENGTH_SHORT).show();

                URLPATH = "https://gong.ggtrr8902.com/zfb?zfbType=" + type + "&userName=" + u + "&money=" + m;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        LoadImage2();
                    }
                }).start();
                break;
            case R.id.del_all:
                delDir(new File(FILEPATH));
                Toast.makeText(getApplicationContext(), "删除完成", Toast.LENGTH_LONG).show();
                break;
        }
    }

    /**
     * 主线程更新UI
     */
    private Handler connectHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mImage.setImageBitmap(mBitmap);
                    mProgressDialog = ProgressDialog.show(MainActivity.this, "保存图片", "图片正在保存中，请稍等...", true);
                    long l = System.currentTimeMillis();
                    String s = FILEPATH +"/" +names+"_"+prices+"_"+type +"_"+ l + ".jpg";
                    SaveImage(s);
                    connectHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Message message = new Message();
                            message.what = 2;
                            connectHandler.sendMessage(message);
                        }
                    }, 100);
                    break;
                case 2:
                    mProgressDialog.dismiss();
                    Toast.makeText(MainActivity.this, "图片保存完成", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    /**
     * 下载图片从输入里面
     */
    private void LoadImage2() {
        try {


            URL url = new URL(URLPATH);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            InputStream inputStream = conn.getInputStream();
            mBitmap = BitmapFactory.decodeStream(inputStream);
            Message message = new Message();
            message.what = 1;
            connectHandler.sendMessage(message);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存图片到sd卡指定目录
     */
    private void SaveImage(String path) {
        verifyStoragePermissions(this);
        Toast.makeText(getApplicationContext(),path,Toast.LENGTH_LONG).show();
        //创建文件 在是的sd卡外部存储
        dirfile = new File(FILEPATH);
        if (!dirfile.exists()) {
            dirfile.mkdir();
        }
        file = new File(path);
        //从系统保存需要用到输出流
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
            //bitmap进行解码
            if (mBitmap == null) {
                Toast.makeText(this, "Kong", Toast.LENGTH_SHORT).show();
                mProgressDialog.cancel();
            } else {
                mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
                bos.hashCode();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(),
                    file.getAbsolutePath(), path, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 判断SDK版本是不是4.4或者高于4.4
            String[] paths = new String[]{file.getAbsolutePath()};
            MediaScannerConnection.scanFile(this, paths, null, null);
        } else {
            final Intent intent;
            if (file.isDirectory()) {
                intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
                intent.setClassName("com.android.providers.media", "com.android.providers.media.MediaScannerReceiver");
                intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
            } else {
                intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intent.setData(Uri.fromFile(file));
            }
            this.sendBroadcast(intent);
        }
    }

    public static void delDir(File file) {
        if (file.isDirectory()) {
            File zFiles[] = file.listFiles();
            for (File file2 : zFiles) {
                delDir(file2);
            }
            file.delete();
        } else {
            file.delete();
        }
    }

}